<template>
  <div>
    <div class="reportcenter">
      <div ref="container" class="container">
        <div class="head">
          <div>
            <label for="datePicker">报表时间:</label>
            <!-- popper-class="date-style"  全局样式内修改了一些class -->
            <el-date-picker
              v-model="datePicker"
              size="small"
              type="month"
              value-format="yyyy-MM"
              placeholder="请选择"
              popper-class="date-style"
              @change="changePickerYear"
            />
          </div>
          <div>
            <el-button
              size="small"
              @click="lookTable"
            >查看</el-button>
            <el-button
              size="small"
              @click="downTable"
            >下载</el-button>

            <el-popover
              v-if="isShowFilterBtn"
              placement="right"
              width="520"
              trigger="click"
            >
              <div class="reportcenter-tableFilter-container">
                <Table-Filter-Form ref="filterForm" :table-title="tableTitle" :year="datePicker" />
              </div>
              <el-button slot="reference" size="small" @click="gotomoreSearch">多条件查询</el-button>
            </el-popover>
            <span v-if="isShowCondition" :title="searchContent" class="conditionClass">根据:<span style="color:red">{{ searchContent }}</span>搜索的结果</span>
          </div>
        </div>
        <div class="title">
          <div class="search">
            <el-input
              v-model="inputSearch"
              size="mini"
              placeholder="请输入搜索关键字"
              suffix-icon="el-icon-search"
              @input="searchTable"
            />
          </div>
          <div style="display:flex">
            <span style="flex:1.5;text-align:center">{{ tableTitle }} </span>
            <!-- <span class="total">共{{ tableData.length }}条数据</span> -->
          </div>

        </div>
        <div>
          <DynamicTable
            ref="DynamicTable"
            :height="tableHeight + ''"
            :fixed-key-left="fixedKeyLeft"
            :table-header="columnList"
            :table-data="tableData1"
            :table-loading="tableLoading"
            :table-title="tableTitle"
            is-border
            show-operator
            @viewClick="viewClick"
          />
        </div>
        <div class="reportcenter-page">
          <el-pagination
            :current-page="pageIndex"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageTotal"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <Dialog :get-table-info="getTableInfo" :out-colunms="columnList" :filter-list="filterList" :date-picker="datePicker" :row-now="rowNow" :is-show="isDialogShow" @dialogClose="dialogClose" />
  </div>
</template>

<script type="text/ecmascript-6">
import DynamicTable from './components/DynamicTables';
import TableFilterForm from '@/views/reportCenter/components/TableFilterForm';
import Dialog from './components/Dialog';
import { exportExcel } from '@/api/monthReport/index.js';
import { downloadFile } from '@/utils/commonMethods.js';
import { Message } from 'element-ui';
import {
  fixedKeyLeft,
  TABLES_INFO,
  getTableInfo,
  showFilterBtnArr
} from './stateData';
export default {
  components: {
    DynamicTable,
    Dialog,
    TableFilterForm
  },
  data() {
    return {
      fixedKeyLeft,
      inputSearch: '',
      datePicker: localStorage.getItem('chooseYear') + '-' + (new Date().getMonth() + 1),
      tableTitle: '',
      tableLoading: false,
      isDialogShow: false,
      tableHeader: [],
      tableData1: [],
      tableData: [],
      columnList: [],
      filterList: [], // 筛选条件
      rowNow: {},
      tableHeight: 0,
      pageIndex: 1,
      pageSizes: [50, 100, 150, 200],
      pageSize: 50,
      pageTotal: 0,
      isShowCondition: false,
      searchContent: ''

    };
  },
  computed: {
    getTableInfo() {
      return TABLES_INFO.find(item => item.title === this.tableTitle);
    },

    isShowFilterBtn() {
      return showFilterBtnArr.includes(this.tableTitle);
    }
  },
  created() {
    this.tableTitle = localStorage.getItem('siderName');
    this.searchTable = this.debounce(this.searchTable, 100);
  },
  mounted() {
    this.tableHeight = this.$refs.container.offsetHeight - 60 - 24 - 20 - 50;
    this.initPage(this.datePicker);
  },
  methods: {
    changePickerYear() {
      if (this.datePicker) {
        this.datePicker = localStorage.getItem('chooseYear') + '-' + this.datePicker.split('-')[1];
      }
    },
    downTable() {
      if (this.tableData1.length === 0) {
        Message({
          message: '暂无数据,无法下载',
          type: 'warning'
        });
      } else {
        exportExcel({
          columnList: this.columnList,
          headerList: this.tableHeader,
          moneyType: '1',
          year: this.datePicker.split('-')[0],
          month: this.datePicker.split('-')[1],
          orderBy: '',
          pageType: '0',
          filterList: []
        }).then(res => {
          downloadFile(res, `${localStorage.getItem('siderName')}.xls`, '.xls');
        });
      }
    },
    gotomoreSearch() {
      this.isShowCondition = false;
      this.searchContent = '';
    },
    lookTable() {
      if (!this.datePicker) {
        Message({
          type: 'warning',
          message: '日期不能为空!'
        });
      } else {
        this.filterList = [];
        this.isShowCondition = false;
        this.searchContent = '';
        this.initPage(this.datePicker);
      }
    },
    handleSizeChange(v) {
      this.pageIndex = 1;
      this.pageSize = v;
      this.initPage(this.datePicker);
    },
    handleCurrentChange(v) {
      this.pageIndex = v;
      this.initPage(this.datePicker);
    },
    dialogClose() {
      this.isDialogShow = false;
      this.rowNow = {};
      this.filterList = [];
    },

    viewClick(row) {
      this.isDialogShow = true;
      this.rowNow = row;
      // CZBGLSUMMARY
      // const filterArr = ['CENTERPRISECODE', 'CENTERPRISENAME', 'CZBGLREMARK', 'CZBGLSUMMARY', 'CKEYPROGRAMNAME', 'CPROGRAMTYPENAME', 'CPROGRAMNAME', 'CRESOURCENAME', 'CBUDGETCATEGORYNAME'];
      this.filterList = Object.keys(row).reduce((prev, key) => {
        const value = row[key];
        if (value && key !== '_XID') {
          const obj = {
            value,
            col: key,
            'symbol': 'eq'
          };
          prev.push(obj);
        }

        return prev;
      }, []);
    },
    searchEvent1(v) {
      if (v) {
        const filterRE = new RegExp(v, 'gi');
        const searchProps = this.tableHeader.reduce((prev, value) => {
          prev.push(value.value);
          return prev;
        }, []);
        const rest = this.tableData.filter(item => searchProps.some(key => {
          return (item[key] + '').indexOf(v) > -1;
        }));
        this.tableData1 = rest.map(row => {
          const item = Object.assign({}, row);
          searchProps.forEach(key => {
            item[key] = (item[key] + '').replace(filterRE, match => `<span class="keyword-lighten">${match}</span>`);
          });
          return item;
        });
      } else {
        this.tableData1 = this.tableData;
      }
    },

    debounce(fn, delay) {
      let timer = null;
      return function(...args) {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          fn.apply(this, args);
        }, delay);
      };
    },

    searchTable(v) {
      this.searchEvent1(v);
    },

    initPage(time) {
      this.tableLoading = true;
      getTableInfo(this.getTableInfo, 'head').then(({ columnList, headerList }) => {
        this.tableHeader = headerList;
        this.columnList = columnList;
        const headerData = [];
        if (localStorage.getItem('siderName').indexOf('工资福利支出情况表') !== -1) {
          if (localStorage.getItem('xcRoleName').indexOf('财政') !== -1) {
            this.columnList.map((item, index) => {
              if (index < 3) {
                headerData.push(item);
              }
            });
          } else {
            const enterpriseList = JSON.parse(localStorage.getItem('enterprise_jc'));
            this.columnList.map((item, index) => {
              if (index === 0 || index === 1) {
                headerData.push(item);
              }
            });
            enterpriseList.map(o => {
              this.columnList.map(a => {
                if (o.NAME.indexOf(a.label) !== -1) {
                  headerData.push(a);
                }
              });
            });
          }
          this.columnList = headerData;
        } else {
          this.columnList = columnList;
        }

        const bodyRequest = {
          columnList,
          headerList,
          moneyType: '1',
          month: time.split('-')[1],
          orderBy: '',
          pageIndex: this.pageIndex - 1,
          pageSize: this.pageSize,
          pageType: '1',
          year: time.split('-')[0],
          bodyUrl: this.getTableInfo.bodyUrl,
          filterList: this.filterList
        };

        getTableInfo(bodyRequest, 'data').then(res => {
          this.pageTotal = res.total;
          if (res.total !== 0) {
            if (localStorage.getItem('siderName').indexOf('工资福利支出情况表') !== -1) {
              this.tableData = res.data.filter(item => item.CFUNCTIONCODE === '501' || item.CFUNCTIONCODE === '50501');
              const emptyCol = [];
              for (const key in this.tableData[0]) {
                if (this.tableData[0][key] === '') {
                  emptyCol.push(key);
                }
              }
              emptyCol.map(o => {
                this.columnList = this.columnList.filter(item => item.value !== o || item.value === 'CNAME');
              });
            } else {
              this.tableData = res.data;
            }

            this.searchEvent1();
          } else {
            this.tableData = [];
            this.tableData1 = [];
          }
          this.tableLoading = false;
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.reportcenter {
  width: calc(100% - 40px);
  height: calc(100vh - 50px - 70px - 33px);
  background-color: #fff;
  margin: 5px 10px;
  border-radius: 4px;
  .container {
    padding: 10px;
    height: 100%;
    .head {
      display: flex;
      padding: 10px 0;
      label {
        font-weight: 500;
      }
      > div {
        margin-right: 20px;
      }
    }
    .total {
      cursor: pointer;
      color: rgba(0,0,0,0.25);
      text-align: right;
      flex:1;
     font-size: 15px;
     line-height: 40px;
    }
  }

  .title {
    text-align: center;
    position: relative;
    font-size: 24px;
    height: 40px;
    font-weight: bolder;
    font-family: PingFangSC, PingFangSC-Medium;
    .search {
      position: absolute;
      left: 0;
    }
  }
}

/deep/ * {
  .el-button {
    color: #1890ff;
    border-color: #1890ff;
  }

}
/deep/ .el-picker-panel {
  .el-picker-panel__body-wrapper {
    background-color: red;
  }
}

.reportcenter-tableFilter-container {
  width: 100%;

}

.reportcenter-page {
  padding: 10px 0;
}
.conditionClass{
    white-space: nowrap;
    width: calc(43vw);
    display: inline-block;
    vertical-align: middle;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
}
</style>
